﻿using Ldt.DataEngine.DataFlowParse.Model;
using LdtJudge.DataEngine.CallInterface;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.CallInterface.ConfigManager;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Ldt.DataEngine.DataFlowParse
{
    /// <summary>
    /// 配置流程解析
    /// </summary>
    public class ConfigFlowLoad
    {
        private string _systemapiurl;
        /// <summary>
        /// 实例化对象
        /// </summary>
        /// <param name="systempapi">systemapi地址</param>
        public ConfigFlowLoad() 
        {
            _systemapiurl = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi");
        }
        /// <summary>
        /// 流程类型
        /// </summary>
        public enum FlowType
        {
            /// <summary>
            /// 分析流程
            /// </summary>
            Ana,
            /// <summary>
            /// 优选流程
            /// </summary>
            Opt,
        }
        /// <summary>
        /// 请求数据流程
        /// </summary>
        /// <param name="requestPara"></param>
        /// <param name="flowType"></param>
        /// <returns></returns>
        public List<ConfigModel> LoadFlowInfo(RequestPara requestPara, FlowType flowType)
        {
            if (!string.IsNullOrEmpty(requestPara.AppId))
            {
                requestPara.processName = requestPara.AppId;
            }
            var dic = ToDic(requestPara);
            string uilocal = "";
            switch (flowType)
            {
                case FlowType.Ana:
                    uilocal = "api/wordparse/GetConfigInfo";
                    break;
                case FlowType.Opt:
                    uilocal = "api/wordparse/GetConfigInfo";
                    break;

            }
            string responsemsg=GetRequest($"{_systemapiurl}/{uilocal}", dic, "utf-8");
            string msgnew = Encoding.UTF8.GetString(Convert.FromBase64String(responsemsg));
            var mo=JsonConvert.DeserializeObject<MsgStruct>(msgnew);
            //if (mo.Result.Code=="1")
            if (mo.Result.Code=="0")
            {
                return mo.Body.ModuleConfig.ToList();
            }
            return new List<ConfigModel>();
        }


        #region HTTP请求
        private string GetRequest(string url, IDictionary<string, string> parameters, string charset)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters, charset);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters, charset);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET");
            req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }
        /// <summary>
        /// 请求对象
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        private HttpWebRequest GetWebRequest(string url, string method, int timeout = 100)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "Aop4Net";
            req.Timeout = timeout * 1000;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);

                // 按字符读取并写入字符串缓冲
                int ch = -1;
                while ((ch = reader.Read()) > -1)
                {
                    // 过滤结束符
                    char c = (char)ch;
                    if (c != '\0')
                    {
                        result.Append(c);
                    }
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }

            return result.ToString();
        }
        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        private string BuildQuery(IDictionary<string, string> parameters, string charset)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");

                    string encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));

                    postData.Append(encodedValue);
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
        #endregion

        /// <summary>
        /// 将对象属性转换为key-value对
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private Dictionary<string, string> ToDic<T>(T o)
        {
            //Dictionary<string, string> dic = new Dictionary<string, string>();
            var d = o.GetType().GetProperties()//这一步获取匿名类的公共属性，返回一个数组
                .OrderBy(q => q.Name)//这一步排序，需要引入System.Linq，当然可以省略
                .Where(q => q.Name != "vs")//这一步筛选，也可以省略
                .ToDictionary(q => q.Name.ToLower(), q => q.GetValue(o)?.ToString());//这一步将数组转换为字典
            return d;
        }


    }
}
